﻿#include "game.h"

#include <algorithm>


void gameInit(Snake* snake, Point* food)
{
	snake->size = 10;
	snake->length = 3;
	snake->dir = RIGHT;
	snake->coords[0] = {100, 50}; // head
	snake->coords[1] = {90, 50};
	snake->coords[2] = {80, 50};
	createFood(food);
}

void display(const Snake* snake, const Point* food)
{
	cleardevice(); // clear the screen when drawing again
	for (int i = 0; i < snake->length; i++)
	{
		setlinecolor(BLUE);
		setfillcolor(GREEN);
		fillrectangle(snake->coords[i].x, snake->coords[i].y,
		              snake->coords[i].x + snake->size, snake->coords[i].y + snake->size);
	}
	setfillcolor(BLUE);
	fillrectangle(food->x, food->y,
	              food->x + snake->size, food->y + snake->size);
}

void snakeMove(Snake* snake)
{
	for (int i = snake->length - 1; i > 0; i--)
	{
		snake->coords[i] = snake->coords[i - 1];
	}
	switch (snake->dir)
	{
	case UP:
		snake->coords[0].y -= SPEED;
		break;
	case DOWN:
		snake->coords[0].y += SPEED;
		break;
	case LEFT:
		snake->coords[0].x -= SPEED;
		break;
	case RIGHT:
		snake->coords[0].x += SPEED;
		break;
	}
}

void changeDirection(Snake* snake)
{
	if (_kbhit())
	{
		const int key = _getch();
		printf("%d\n", key);

		switch (key)
		{
		case 72: // up
			if (snake->dir == DOWN) break; // prevent reverse
			snake->dir = UP;
			break;
		case 80: // down
			if (snake->dir == UP) break; // prevent reverse
			snake->dir = DOWN;
			break;
		case 75: // left
			if (snake->dir == RIGHT) break; // prevent reverse
			snake->dir = LEFT;
			break;
		case 77: // right
			if (snake->dir == LEFT) break; // prevent reverse
			snake->dir = RIGHT;
			break;
		default: ;
		}
	}
}

void createFood(Point* food)
{
	food->x = rand() % (WIDTH / 10) *10;
	food->y = rand() % (HEIGHT / 10) *10;
}

bool isEaten(Snake *snake, Point *food)
{
	if (snake->coords[0].x == food->x && snake->coords[0].y == food->y) return true;
	return false;
}
